package com.parlons;

import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.os.Looper;
import android.util.*;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.NetworkOnMainThreadException;
import android.support.annotation.Nullable;
import android.widget.ListView;

import com.parlons.activities.ChatActivity;
import com.parlons.activities.ChatFragment;
import com.parlons.activities.MainActivity;

import java.util.*;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.io.*;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.jivesoftware.smack.*;
import org.jivesoftware.smackx.*;
import org.jivesoftware.smack.util.*;
import org.jivesoftware.smackx.workgroup.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.proxy.*;
import org.jivesoftware.smack.provider.*;
import org.jivesoftware.smack.util.collections.*;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * chat listener
 *
 * @author Administrator
 */
public class TaxiChatManagerListener implements ChatManagerListener {
    public static Handler UIHandler = new Handler(Looper.getMainLooper());
    private Context context;

    TaxiChatManagerListener(Context c) {
        context = c;
    }

    public void chatCreated(Chat chat, boolean arg1) {
        chat.addMessageListener(new MessageListener() {
            public void processMessage(Chat arg0, Message msg) {
                StringUtils.parseName(SmackServices.getConnection().getUser());
                final String sender = SmackServices.getUserNameFromJID(msg.getFrom());
                final String receiver = SmackServices.getUserNameFromJID(msg.getTo());
                String body = msg.getBody();
                System.out.println("---------------------"+body);
                final String friendUsername = (sender.equals(SmackServices.getUserName())) ? receiver : sender;

                // add the message to db
                DatabaseServices DBService = DatabaseServices.getInstance(context);
                DBService.addMessage(sender, receiver, body, SmackServices.getUserName());
                // add or update a chat in the chat list
                DBService.addOrUpdateChat(SmackServices.getUserName(), friendUsername, body);
                // if receive a message, add unread by 1
                if (sender.equals(friendUsername))
                    DBService.addUnread(SmackServices.getUserName(), friendUsername);
                // if talking with the sender, set it to 0
                if (ChatActivity.friendName!=null && sender.equals(ChatActivity.friendName))
                    DBService.resetUnread(SmackServices.getUserName(), sender);
                // get the total unread number
                MainActivity.fragmentManager.invalidateOptionsMenu();

                DBService.close();

                UIHandler.post(new Runnable() {
                    /** Update the chat screen if initialized */
                    @Override
                    public void run() {
                        /** Update chat */
                        if (ChatActivity.friendName != null && ChatActivity.friendName.equals(sender)) {
                            if (ChatActivity.simpleCursorAdapter == null)
                                System.out.println("adapter null");
                            DatabaseServices DBService = DatabaseServices.getInstance(context);
                            Cursor cursor = DBService.getMessageCursor(sender, receiver, SmackServices.getUserName()); //the order doesn't matter
                            if (cursor == null)
                                System.out.println("cursor null");
                            if (ChatActivity.simpleCursorAdapter != null) {
                                ChatActivity.simpleCursorAdapter.changeCursor(cursor);
                                ChatActivity.moveToBottom();
                            }
                        }

                        /** Update chat list */
                        if (ChatFragment.simpleCursorAdapter != null) {
                            DatabaseServices DBService = DatabaseServices.getInstance(context);
                            Cursor cursor = DBService.getChatCursor(SmackServices.getUserName()); //the order doesn't matter
                            if (cursor == null)
                                System.out.println("cursor null");
                            if (ChatFragment.simpleCursorAdapter != null) {
                                ChatFragment.simpleCursorAdapter.changeCursor(cursor);
                            }
                        }
                    }
                });

                //TODO: this parts actually parse the message that is in JSON style
                boolean left = body.substring(0, 1).equals("{");
                boolean right = body.substring(body.length() - 1, body.length()).equals("}");
                if (left && right) {
                    try {
                        JSONObject obj = new JSONObject(body);
                        String type = obj.getString("messageType");
                        String chanId = obj.getString("chanId");
                        String chanName = obj.getString("chanName");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }
}
